/*******************************************************************************
* Copyright (c) 2010, 2018 西安秦晔信息科技有限公司
* Licensed under the Apache License, Version 2.0 (the "License");
*    you may not use this file except in compliance with the License.
*    You may obtain a copy of the License at
*
*       http://www.apache.org/licenses/LICENSE-2.0
*
*    Unless required by applicable law or agreed to in writing, software
*    distributed under the License is distributed on an "AS IS" BASIS,
*    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*    See the License for the specific language governing permissions and
*    limitations under the License.
*******************************************************************************/
package com.qinyeit.webapp.controller.management.stores;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.qinyeit.serviceapp.entity.Material;
import com.qinyeit.serviceapp.entity.Stock;
import com.qinyeit.serviceapp.entity.TransferOrder;
import com.qinyeit.serviceapp.entity.TransferOrderDetail;
import com.qinyeit.serviceapp.entity.enums.State;
import com.qinyeit.serviceapp.entity.enums.TransferState;
import com.qinyeit.serviceapp.service.materials.MaterialService;
import com.qinyeit.serviceapp.service.stores.StockService;
import com.qinyeit.serviceapp.service.stores.TransferOrderDetailService;
import com.qinyeit.serviceapp.service.stores.TransferOrderService;
import com.qinyeit.serviceapp.service.stores.WarehouseService;
import com.qinyeit.webapp.controller.management.BaseManagementController;
import com.qinyeit.webapp.utils.CurrentAccountUtils;
import com.qinyeit.webapp.utils.SearchableUtils;
import com.qinyetech.springstage.core.entity.search.Searchable;
import com.qinyetech.springstage.core.lang.QyMap;
import com.qinyetech.springstage.core.utils.JSONUtils;
import com.qinyetech.springstage.core.web.annotation.PageableDefaults;
import com.qinyetech.springstage.core.web.annotation.PermissionInfo;
import com.qinyetech.springstage.core.web.dto.ResponseResult;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * ClassName: TransferOrdersController <br/>
 * Function: transferOrder [调拨单据] <br/>
 * date: 2018-11-08 14:02:44 <br/>
 *
 * @author liuwenjin
 * @version  1.0
 * @since JDK 1.8
 */
@RestController
@RequestMapping("/management/stores/transferOrders")
@PermissionInfo(parentName ="基础信息管理" ,parentOrder = 10,order = 10,code = "management_transferOrder:read",name ="调拨单据",deleteAble = false)
public class TransferOrdersController extends BaseManagementController{

	@Autowired
	private TransferOrderService transferOrderService;
	@Autowired
    private WarehouseService warehouseService;
	@Autowired
    private TransferOrderDetailService transferOrderDetailService;
	@Autowired
    private MaterialService materialService;
	@Autowired
    private StockService stockService;
    //TODO include的字段,支持jsonPath
	private final String [] keys = {"id","no","transferOutId","transferInId","operator","operateTime","amount","state","remark",
            "transferOutName","transferInName","operator","operatorName"};
	private final String [] detailkeys = {"id","materialId","no","name","spec","unit","count","price","amount","remark","code"};


    @RequiresPermissions("management_transferOrder:show")
    @PermissionInfo(code = "management_transferOrder:show",name ="查看",deleteAble = false)
    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST})
    @PageableDefaults(sort = "id=desc")//默认按照id降序
    public ResponseResult<JSONObject> index(Searchable searchable){
        searchable = SearchableUtils.newSearchableWithMerchantFilter(searchable);
        Page<TransferOrder> transferOrderPage = transferOrderService.findAll(searchable);

        return ok("查询成功", JSONUtils.include(transferOrderPage,new Class[]{TransferState.class}, keys));
    }



    @GetMapping("/create")
    public ResponseResult<QyMap> _new(Long id){
        QyMap map=QyMap.NEW();
        if(id==null){
            map.setv("transferOrder",JSONUtils.include(new TransferOrder(), keys));
        }else{
            TransferOrder transferOrder = transferOrderService.findById(id);
            map.setv("transferOrder",JSONUtils.include(transferOrder, keys));
            Searchable searchable = SearchableUtils.newSearchableWithMerchantFilter();
            searchable.addSearchParam("order.id_eq",id);
            List<TransferOrderDetail> detailList = transferOrderDetailService.findWithSort(searchable);
            map.setv("detailList",JSONUtils.include(detailList,detailkeys));
            List<Map<String,Object>> materials = Lists.newArrayList();
            QyMap item = null;
            Material material = null;
            Stock stock = null;
            if(CollectionUtils.isNotEmpty(detailList)){
                for (TransferOrderDetail detail : detailList) {
                    material = materialService.findById(detail.getMaterialId());
                    stock = stockService.getStocks(transferOrder.getTransferOutId(),detail.getMaterialId(),CurrentAccountUtils.getAuthenticatedMerchantGroupID());
                    item = QyMap.NEW();
                    if(material==null){
                        item.setv("material_unit","");
                    }else {
                        item.setv("material_unit",material.getUnit());
                    }
                    item.setv("material_id",detail.getMaterialId());
                    item.setv("matrial_name",detail.getName());
                    item.setv("material_no", detail.getNo());
                    item.setv("goods_spec", detail.getSpec());

                    if(stock==null){
                        item.setv("cost",0);
                        item.setv("count",0);
                        item.setv("amount",0);
                    }else {
                        item.setv("cost",stock.getCost());
                        item.setv("count",stock.getCount());
                        item.setv("amount",stock.getAmount());
                    }
                    materials.add(item);
                }
            }
            map.setv("materials",materials);

        }

        initFormDate(map);
        return ok("初始化成功", map);
    }

    @RequiresPermissions("management_transferOrder:create")
    @PermissionInfo(code = "management_transferOrder:create",name ="新增",deleteAble = false)
    @PostMapping("/create")
    public ResponseResult<String> create(@RequestBody JSONObject transferOrder, BindingResult bindingResult){
//        if(transferOrderService.exists(buildExists(null, "no", transferOrder.getNo()))){
//             bindingResult.rejectValue("no","no.error","编号已经存在");
//        }
        if (bindingResult.hasErrors()) {
            return super.validateFail(bindingResult);
        }
        transferOrderService.saveData(transferOrder,CurrentAccountUtils.getAuthenticatedMerchantGroupID());
        return ok("保存成功");
    }

    @GetMapping("/{id}")
    public ResponseResult<JSONObject> show(@ModelAttribute TransferOrder transferOrder){
        return ok("查询成功", JSONUtils.include(transferOrder, keys));
    }

    @GetMapping("/{id}/update")
    public ResponseResult<QyMap> edit(@ModelAttribute TransferOrder transferOrder){
        QyMap map=QyMap.NEW();
        map.setv("transferOrder",JSONUtils.include(transferOrder, keys));
        initFormDate(map); //TODO 如果没有需要初始化的数据，测则删除该行
        return ok("查询成功",map);
    }

    @RequiresPermissions("management_transferOrder:update")
    @PermissionInfo(code = "management_transferOrder:update",name ="修改",deleteAble = false)
    @PutMapping("/{id}/update")
    public ResponseResult<String> update(@RequestBody JSONObject transferOrder,BindingResult bindingResult){
//        if(transferOrderService.exists(buildExists(null, "no", transferOrder.getNo()))){
//             bindingResult.rejectValue("no","no.error","编号已经存在");
//        }
        if (bindingResult.hasErrors()) {
            return super.validateFail(bindingResult);
        }
        transferOrderService.saveData(transferOrder, CurrentAccountUtils.getAuthenticatedMerchantGroupID());
        return ok("更新成功", null);
    }

    @RequiresPermissions("management_transferOrder:destory")
    @PermissionInfo(code = "management_transferOrder:destory",name ="删除",deleteAble = false)
    @DeleteMapping("/{id}")
    public ResponseResult<String> destory(@PathVariable Long id){
        transferOrderService.logicDelete(id);
        return ok("删除成功", null);
    }

    @ModelAttribute
    public void preparedData(@PathVariable(value="id",required = false) String id,Model model){
        if(StringUtils.isNotBlank(id)){ //如果路径中有id参数则查询实体对象
            TransferOrder transferOrder = transferOrderService.findById(Long.valueOf(id));
            model.addAttribute(transferOrder);
        }
    }

    /**
     * 初始化表单数据
     * @param qyMap
     */
    private void initFormDate(QyMap qyMap){

        //仓库
        qyMap.setv("warehouses",JSONUtils.include(warehouseService.findWithSort(
                SearchableUtils.newSearchableWithMerchantFilter()),new Class[]{State.class},
                "id","no","name","state","sys"));
    }

}